<template>
    <div class="app-container">
      <el-row :gutter="20">
        <!-- 左侧树形结构 -->
        <el-col :span="5">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <!-- 添加过滤输入框 -->
              <el-input
                placeholder="搜索门店所在城市"
                v-model="filterText"
                size="mini"
                style="width: calc(100% - 50px);"
              ></el-input>
            </div>
            <div v-loading="treeLoading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.8)">
              <el-tree
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
                highlight-current
                node-key="id"
                ref="tree"
                :filter-node-method="filterNode"
                :default-expanded-keys="expandedKeys"
              ></el-tree>
            </div>
          </el-card>
        </el-col>
        
        <!-- 右侧门店列表 -->
        <el-col :span="19">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="门店名称" prop="storeName">
              <el-input
                v-model="queryParams.storeName"
                placeholder="请输入门店名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="门店状态" clearable size="small">
                <el-option
                  v-for="dict in dict.type.store_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['stores:store:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['stores:store:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['stores:store:remove']"
              >删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>
  
          <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="门店名称" align="center" prop="storeName" v-if="columns[0].visible"/>
            <el-table-column label="省份" align="center" prop="province" v-if="columns[1].visible"/>
            <el-table-column label="城市" align="center" prop="city" v-if="columns[2].visible"/>
            <el-table-column label="区/县" align="center" prop="district" v-if="columns[3].visible"/>
            <el-table-column label="详细地址" align="center" prop="address" :show-overflow-tooltip="true" v-if="columns[4].visible"/>
            <el-table-column label="负责人" align="center" prop="contactPerson" v-if="columns[5].visible"/>
            <el-table-column label="联系电话" align="center" prop="contactPhone" v-if="columns[6].visible"/>
            <el-table-column label="营业时间" align="center" prop="businessHours" v-if="columns[7].visible"/>
            <el-table-column label="状态" align="center" prop="status" v-if="columns[8].visible">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.store_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                  v-hasPermi="['stores:store:query']"
                >查看</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['stores:store:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['stores:store:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
  
      <!-- 添加或修改门店对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所在地区" prop="cityId">
                <el-cascader
                  v-model="form.cityId"
                  :options="areaOptions"
                  :props="{
                    value: 'areaId',
                    label: 'name',
                    children: 'children',
                    emitPath: true
                  }"
                  placeholder="请选择所在地区"
                  clearable
                  @change="handleAreaChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="门店名称" prop="storeName">
                <el-input v-model="form.storeName" placeholder="请输入门店名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="营业时间" prop="businessHours">
                <el-input v-model="form.businessHours" placeholder="请输入营业时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <div class="el-radio-group" role="radiogroup">
                  <label
                    v-for="dict in dict.type.store_status"
                    :key="dict.value"
                    class="el-radio"
                    :class="{ 'is-checked': form.status === dict.value }"
                  >
                    <input
                      type="radio"
                      class="el-radio__input"
                      :value="dict.value"
                      v-model="form.status"
                    >
                    <span class="el-radio__label">{{dict.label}}</span>
                  </label>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="门店描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 查看门店详情对话框 -->
      <el-dialog title="门店详情" :visible.sync="viewOpen" width="780px" append-to-body>
        <el-form ref="viewForm" :model="viewForm" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="省份">
                <el-input v-model="viewForm.province" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="城市">
                <el-input v-model="viewForm.city" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="门店名称">
                <el-input v-model="viewForm.storeName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区/县">
                <el-input v-model="viewForm.district" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="详细地址">
            <el-input v-model="viewForm.address" type="textarea" disabled />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人">
                <el-input v-model="viewForm.contactPerson" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="viewForm.contactPhone" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="营业时间">
                <el-input v-model="viewForm.businessHours" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <dict-tag :options="dict.type.store_status" :value="viewForm.status"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="门店描述">
            <el-input v-model="viewForm.description" type="textarea" disabled />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listStore, getStore, delStore, addStore, updateStore } from "@/api/stores/store";
  import { mapState, mapActions } from 'vuex';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  
  export default {
    name: 'Store',
    dicts: ['store_status'],
    components: { Treeselect },
    computed: {
      ...mapState('area', ['areaData', 'loading: areaLoading']),
      // 修改计算属性获取需要展开的节点ID
      expandedKeys() {
        const keys = []
        // 添加根节点ID
        if (this.treeData && this.treeData.length > 0) {
          keys.push(this.treeData[0].id)
        }
        return keys
      }
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 门店列表数据 (用于右侧表格)
        storeList: [],
        // 树形数据
        treeData: [],
        // 树形配置
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          storeName: undefined,
          province: undefined,
          city: undefined,
          district: undefined,
          status: undefined
        },
        columns: [
          { key: 0, label: `门店名称`, visible: true },
          { key: 1, label: `省份`, visible: true },
          { key: 2, label: `城市`, visible: true },
          { key: 3, label: `区/县`, visible: true },
          { key: 4, label: `详细地址`, visible: true },
          { key: 5, label: `联系人`, visible: true },
          { key: 6, label: `联系电话`, visible: true },
          { key: 7, label: `营业时间`, visible: true },
          { key: 8, label: `状态`, visible: true },
        ],
        
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          cityId: [
            { required: true, message: '所在地区不能为空', trigger: 'change' }
          ],
          storeName: [
            { required: true, message: '门店名称不能为空', trigger: 'blur' }
          ],
          contactPerson: [
            { required: true, message: '联系人不能为空', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '联系电话不能为空', trigger: 'blur' }
          ],
          businessHours: [
            { required: true, message: '营业时间不能为空', trigger: 'blur' }
          ]
        },
        // 是否显示查看弹出层
        viewOpen: false,
        // 查看表单参数
        viewForm: {},
        // 过滤文本
        filterText: '',
        // 是否展开
        isExpanded: true,
        // 树形控件加载状态
        treeLoading: false,
        // 地区选项
        areaOptions: [],
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      areaData: {
        handler(newVal) {
          if (newVal && newVal.provinces.length > 0) {
            this.initTreeData()
          }
        },
        deep: true
      }
    },
    created() {
      this.initTreeData()
    },
    methods: {
      ...mapActions('area', ['preloadAreaData']),
      
      /** 初始化树形数据 */
      async initTreeData() {
        try {
          this.treeLoading = true
          
          // 如果 Vuex 中没有数据，尝试预加载
          if (!this.areaData.provinces.length) {
            await this.preloadAreaData()
          }
          
          // 构建树形数据
          this.treeData = [{
            id: 'root',
            name: '所有门店',
            type: 'all',
            children: this.buildProvinceNodesFromCache()
          }]
          
          // 构建级联选择器数据
          this.areaOptions = this.buildCascaderOptionsFromCache()
          
          // 默认显示所有门店
          this.handleNodeClick({ id: 'root', type: 'all' })

          // 在下一个 tick 中设置展开的节点
          this.$nextTick(() => {
            this.setDefaultExpandedNodes()
          })
        } catch (error) {
          console.error('初始化树形数据失败:', error)
          this.$modal.msgError('初始化树形数据失败，请刷新页面重试')
        } finally {
          this.treeLoading = false
        }
      },
      
      /** 从缓存构建省份节点 */
      buildProvinceNodesFromCache() {
        const provinceNodes = []
        
        for (const province of this.areaData.provinces) {
          const provinceNode = {
            id: province.areaId,
            name: province.name,
            type: 'province',
            children: []
          }
          
          // 从缓存中获取城市数据
          const cities = this.areaData.cities[province.areaId] || []
          
          // 构建城市节点
          for (const city of cities) {
            const cityNode = {
              id: city.areaId,
              name: city.name,
              type: 'city',
              children: []
            }
            
            // 从缓存中获取区县数据
            const districts = this.areaData.districts[city.areaId] || []
            
            // 构建区县节点
            cityNode.children = districts.map(district => ({
              id: district.areaId,
              name: district.name,
              type: 'district'
            }))
            
            provinceNode.children.push(cityNode)
          }
          
          provinceNodes.push(provinceNode)
        }
        
        return provinceNodes
      },
      
      /** 构建级联选择器选项 */
      buildCascaderOptionsFromCache() {
        const options = []
        
        for (const province of this.areaData.provinces) {
          const provinceOption = {
            areaId: province.areaId,
            name: province.name,
            children: []
          }
          
          // 从缓存中获取城市数据
          const cities = this.areaData.cities[province.areaId] || []
          
          // 构建城市选项
          for (const city of cities) {
            const cityOption = {
              areaId: city.areaId,
              name: city.name,
              children: []
            }
            
            // 从缓存中获取区县数据
            const districts = this.areaData.districts[city.areaId] || []
            
            // 构建区县选项
            cityOption.children = districts.map(district => ({
              areaId: district.areaId,
              name: district.name
            }))
            
            provinceOption.children.push(cityOption)
          }
          
          options.push(provinceOption)
        }
        
        return options
      },
      /** 节点点击事件 */
      handleNodeClick(data) {
        this.queryParams.pageNum = 1
        this.queryParams.storeName = undefined
        
        switch (data.type) {
          case 'province':
            this.queryParams.province = data.name
            this.queryParams.city = undefined
            this.queryParams.district = undefined
            break
          case 'city':
            const province = this.findParentProvince(data.id)
            this.queryParams.province = province.name
            this.queryParams.city = data.name
            this.queryParams.district = undefined
            break
          case 'district':
            const city = this.findParentCity(data.id)
            const province2 = this.findParentProvince(city.areaId)
            this.queryParams.province = province2.name
            this.queryParams.city = city.name
            this.queryParams.district = data.name
            break
          default: // 'all'
            this.queryParams.province = undefined
            this.queryParams.city = undefined
            this.queryParams.district = undefined
        }
        
        // 确保查询参数正确设置
        this.queryParams = {
          ...this.queryParams,
          pageNum: 1,
          pageSize: 10
        }
        
        // 添加日志输出
        console.log('查询参数:', this.queryParams)
        
        // 调用查询方法
        this.getList()
      },
      
      /** 查找父级省份 */
      findParentProvince(cityId) {
        for (const province of this.areaData.provinces) {
          const city = this.areaData.cities[province.areaId]?.find(c => c.areaId === cityId)
          if (city) {
            return province
          }
        }
        return null
      },
      
      /** 查找父级城市 */
      findParentCity(districtId) {
        for (const province of this.areaData.provinces) {
          for (const city of this.areaData.cities[province.areaId] || []) {
            const district = this.areaData.districts[city.areaId]?.find(d => d.areaId === districtId)
            if (district) {
              return city
            }
          }
        }
        return null
      },
      
      /** 查询门店列表 */
      getList() {
        this.loading = true
        // 确保查询参数正确
        const params = {
          ...this.queryParams,
          pageNum: this.queryParams.pageNum || 1,
          pageSize: this.queryParams.pageSize || 10
        }
        
        // 添加日志输出
        console.log('发送请求参数:', params)
        
        listStore(params).then(response => {
          console.log('查询响应:', response)
          this.storeList = response.rows
          this.total = response.total
          this.loading = false
        }).catch(error => {
          console.error('查询失败:', error)
          this.loading = false
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          storeName: undefined,
          province: undefined,
          city: undefined,
          district: undefined,
          status: undefined
        }
        this.getList()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加门店'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids[0]
        getStore(id).then(response => {
          this.form = response.data
          // 如果有cityId，需要找到对应的地区路径
          if (this.form.cityId) {
            const areaPath = this.findAreaPathById(this.form.cityId)
            if (areaPath) {
              // 保持 cityId 为单个值，只用于级联选择器的显示
              this.form.cityId = parseInt(this.form.cityId)
            }
          }
          this.open = true
          this.title = '修改门店'
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              updateStore(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.initTreeData() // Refresh tree and list after update
              })
            } else {
              addStore(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.initTreeData() // Refresh tree and list after add
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除门店编号为"' + ids + '"的数据项？').then(function() {
          return delStore(ids)
        }).then(() => {
          this.initTreeData() // Refresh tree and list after delete
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {})
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.viewForm = row
        this.viewOpen = true
      },
      // 过滤节点
      filterNode(value, data) {
        if (!value) return true;
        // 如果是根节点（所有门店），不进行过滤
        if (data.type === 'all') return true;
        // 根据节点类型进行不同的过滤
        switch (data.type) {
          case 'province':
            // 省份节点：检查省份名称和其下所有城市名称
            return data.name.toLowerCase().includes(value.toLowerCase()) ||
                   data.children.some(city => city.name.toLowerCase().includes(value.toLowerCase()));
          case 'city':
            // 城市节点：检查城市名称和其下所有区县名称
            return data.name.toLowerCase().includes(value.toLowerCase()) ||
                   data.children.some(district => district.name.toLowerCase().includes(value.toLowerCase()));
          case 'district':
            // 区县节点：只检查区县名称
            return data.name.toLowerCase().includes(value.toLowerCase());
          default:
            return true;
        }
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          storeName: undefined,
          cityId: undefined,
          address: undefined,
          contactPerson: undefined,
          contactPhone: undefined,
          businessHours: '09:00-21:00',
          description: undefined,
          sortOrder: 0,
          status: '1'
        }
        this.resetForm('form')
      },
      /** 处理地区选择变化 */
      handleAreaChange(value) {
        if (value && value.length > 0) {
          // 获取最后选择的地区ID（可能是省份、城市或区县）
          const selectedAreaId = value[value.length - 1]
          // 确保 selectedAreaId 是数字类型
          this.form.cityId = parseInt(selectedAreaId)
        } else {
          this.form.cityId = undefined
        }
      },
      /** 根据ID查找地区 */
      findAreaById(areaId) {
        // 在省份中查找
        const province = this.areaData.provinces.find(p => p.areaId === areaId)
        if (province) return province

        // 在城市中查找
        for (const province of this.areaData.provinces) {
          const city = this.areaData.cities[province.areaId]?.find(c => c.areaId === areaId)
          if (city) return city
        }

        // 在区县中查找
        for (const province of this.areaData.provinces) {
          for (const city of this.areaData.cities[province.areaId] || []) {
            const district = this.areaData.districts[city.areaId]?.find(d => d.areaId === areaId)
            if (district) return district
          }
        }

        return null
      },
      /** 查找地区路径 */
      findAreaPathById(areaId) {
        // 在区县中查找
        for (const province of this.areaData.provinces) {
          for (const city of this.areaData.cities[province.areaId] || []) {
            const district = this.areaData.districts[city.areaId]?.find(d => d.areaId === areaId)
            if (district) {
              return [province.areaId, city.areaId, district.areaId]
            }
          }
        }

        // 在城市中查找
        for (const province of this.areaData.provinces) {
          const city = this.areaData.cities[province.areaId]?.find(c => c.areaId === areaId)
          if (city) {
            return [province.areaId, city.areaId]
          }
        }

        // 在省份中查找
        const province = this.areaData.provinces.find(p => p.areaId === areaId)
        if (province) {
          return [province.areaId]
        }

        return null
      },
      /** 设置默认展开的节点 */
      setDefaultExpandedNodes() {
        if (this.$refs.tree) {
          // 展开根节点
          this.$refs.tree.store.setExpandedKeys(['root'])
          
          // 获取所有省份节点
          const provinceNodes = this.treeData[0].children || []
          const expandedKeys = ['root']
          
          // 添加所有省份和城市的ID
          provinceNodes.forEach(province => {
            expandedKeys.push(province.id)
            const cityNodes = province.children || []
            cityNodes.forEach(city => {
              expandedKeys.push(city.id)
            })
          })
          
          // 设置展开的节点
          this.$refs.tree.store.setExpandedKeys(expandedKeys)
        }
      },
    }
  }
  </script>
  
  <style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  /* 添加左侧树形结构的滚动样式 */
  .box-card {
    /* height: calc(100vh - 120px); */ /* 移除固定的高度，让其在 flex 容器中自适应 */
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%; /* 确保在父容器允许的情况下占满高度 */
  }

  .box-card .el-card__body {
    flex: 1;
    overflow-y: auto; /* 只允许垂直方向滚动 */
    padding: 10px;
  }

  /* 确保树形结构在滚动时保持固定宽度 */
  .el-tree {
    width: 100%;
  }

  /* 可能需要为父容器el-col设置一个高度，以让flex子项box-card继承 */
  .el-col[data-v-xxxxxxx] { /* 注意这里的 data-v-xxxxxxx 需要替换为实际的scoped hash */
      height: 100%;
  }
  </style>
